package com.moyu.auth.service.impl;

import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.moyu.auth.client.UserClient;
import com.moyu.auth.dto.User;
import com.moyu.auth.dto.UserLoginDTO;
import com.moyu.auth.dto.UserRegDTO;
import com.moyu.auth.service.ILoginAndRegService;
import com.moyu.common.core.enums.ResultCode;
import com.moyu.common.core.utils.BCryptUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 登录注册相关操作服务层
 *
 * @Author 赵彦博
 * @Date 2024/12/30 16:43
 */
@Service
public class LoginAndRegServiceImpl implements ILoginAndRegService {

    @Autowired
    private UserClient userClient;

    @Override
    public SaResult doLogin(UserLoginDTO userLoginDTO) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        User user = userClient.query(userLoginDTO.getAccount()).getData();
        if (user == null) {
            return SaResult.error(ResultCode.FAILED_USER_NOT_EXISTS.getMsg());
        }
        if (BCryptUtils.matchesPassword(userLoginDTO.getPassword(), user.getPassword())) {
            StpUtil.setStpLogic(new StpLogicJwtForSimple());
            StpUtil.login(user.getId());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            System.out.println(tokenInfo);
            return SaResult.ok("登录成功").setData(tokenInfo);
        }
        return SaResult.error(ResultCode.FAILED_LOGIN.getMsg());
    }

    @Override
    public int reg(UserRegDTO userRegDTO) {
        return userClient.reg(userRegDTO);
    }
}
